package com.example.jdbc.server.controller;

import com.example.jdbc.server.service.JdbcService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class JdbcController {

    @Autowired
    private JdbcService jdbcService;

    @PostMapping("/execute")
    public Map<String, Object> execute(@RequestBody Map<String, Object> request) throws SQLException {
        String sql = (String) request.get("sql");
        return jdbcService.execute(sql);
    }

    @PostMapping("/executeUpdate")
    public Map<String, Object> executeUpdate(@RequestBody Map<String, Object> request) throws SQLException {
        String sql = (String) request.get("sql");
        int updateCount = jdbcService.executeUpdate(sql);
        Map<String, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("updateCount", updateCount);
        return objectObjectHashMap;
    }

    @PostMapping("/commit")
    public void commit() throws SQLException {
        jdbcService.commit();
    }

    @PostMapping("/rollback")
    public void rollback() throws SQLException {
        jdbcService.rollback();
    }
}